const date = {}
/**
 * 将时间格式化为指定格式的时间
 * @param {指定格式化的时间} date 
 * @param {指定格式} fmt 
 * @returns 返回指定格式的时间
*/
date.formatDate = function (date, fmt) {
  function padLeftZero(str) {
    return ("00" + str).substr(str.length)
  }

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
  }

  let obj = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  }

  for (let key in obj) {
    if (new RegExp(`(${key})`).test(fmt)) {
      let str = obj[key] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
    }
  }
  return fmt
}

/**
 * 将时间格式化为指定的时间
 * @param {指定时间类型} type
 * @param {数字} num 
 * @returns 返回指定的时间
*/
date.getPointDate = function (type, num) {
  var now = new Date();
  switch (type) {
    case "year":  //获取num年前后的时间
      now.setFullYear(now.getFullYear() + num);
      var y = now.getFullYear();
      var m = now.getMonth() + 1;
      var d = now.getDate();
      var pointDate = y + "-" + m + "-" + d + " 00:00:00";
      break;
    case "month":  //获取num月前后的时间
      now.setMonth(now.getMonth() + num);
      var y = now.getFullYear();
      var m = now.getMonth() + 1;
      var d = now.getDate();
      var pointDate = y + "-" + m + "-" + d + " 00:00:00";
      break;
    case "week":  //获取num周前后的时间
      var weekDate = new Date(now + (7 * 24 * 3600 * 1000) * num)
      var y = weekDate.getFullYear();
      var m = weekDate.getMonth() + 1;
      var d = weekDate.getDate();
      var pointDate = y + "-" + m + "-" + d + " 00:00:00";
      break;
    case "day":  //获取num天前后的时间
      now.setTime(now.getTime() + (24 * 3600 * 1000) * num);
      var y = now.getFullYear();
      var m = now.getMonth() + 1;
      var d = now.getDate();
      var pointDate = y + "-" + m + "-" + d + " 00:00:00";
      break;
    default:  //获取当前时间
      var y = now.getFullYear();
      var m = now.getMonth() + 1;
      var d = now.getDate();
      var pointDate = y + "-" + m + "-" + d + " 00:00:00";
  }
  return pointDate;  //返回指定时间
}

/**
 * 获取时间戳
 * @param {Date} val
 */
date.timestamp = function (val) {
  return new Date().getTime(val);
}

//获取今日日期字符串
date.dayDateString = function (time) {
  const date = new Date(time);
  var month = date.getMonth() + 1;
  var day = [];
  day[0] = date.getFullYear();
  day[1] = month < 10 ? '0' + month : month;
  day[2] = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return day.join('-');
}

//获取当前时间字符串
date.timeString = function () {
  return new Date().toLocaleTimeString('chinese', {
    hour12: false
  });
}

// 获取当前时间（格式 yyyy-MM-dd HH:mm:ss）
date.currentTimeToString = function () {
  let currTime = `${date.dayDateString(new Date())} ${date.timeString()}`
  return currTime;
}

/**
 * 获取指定时间的指定格式
 * @param {String} type 返回格式 date日期 time时间 datetime日期+时间
 * @param {String} time 指定时间 默认为当前时间
 * @returns 
 */
date.currDate = function(type, time) {
	switch(type) {
		case 'date':
			return this.dayDateString(time);
		case 'time':
			return this.timeString(time);
		case 'datetime':
			return `${this.dayDateString(time)} ${this.timeString(time)}`;
		default:
			return `${this.dayDateString(time)} ${this.timeString(time)}`;
	}
}

//获取多少天之前或之后
date.getHowDay = function (day) {
  var date1 = new Date().getTime();
  var date2 = date1 - day * 24 * 60 * 60 * 1000;
  return [this.dayDateString(date2), this.dayDateString(date1)];
},

//限制日期范围
date.disabledDate = function (type) {
  return {
    disabledDate(time) {
      return type ? time.getTime() < Date.now() - 8.64e7 : time.getTime() > Date.now() - 8.64e7 + 24 * 60 * 60 * 1000;
    }
  }
}

/**
 * 区间格式处理
 * @param {Array|String} times 
 * @returns {Array|String} - 若参数 times 为字符串，则以-分割字符串，返回字符串数组
 *                         - 若参数 times 为数组，则遍历数组并拼接成以-区分数组项的字符串，并返回
 */
date.formatTimePicker = function (times) {
  function getType(obj) {
    return (obj === null && 'Null') || (obj === undefined && 'Undefined') || Object.prototype.toString.call(obj).slice(8, -1);
  }
  let dataType = getType(times);
  if (dataType == 'String') {
    return times.split(',');
  } else if (dataType == 'Array') {
    let timesStr = '';
    times.forEach((item, index, arr) => {
      if (index < arr.length - 1) {
        timesStr = `${timesStr}${item},`
      } else {
        timesStr = `${timesStr}${item}`
      }
    });
    return timesStr;
  } else {
    return times;
  }
}


/**
 * 返回year年month月这个月有多少天。
 * @param {Number} year 
 * @param {Number} month 
 * @returns {Number} checkDateTotalDays(2020, 2) =》 结果为2020年2月这个月有多少天 =》 29天
 */
date.checkDateTotalDays = function (year, month) {
  let date = new Date(year, month, 1);
  return new Date(date.getTime() - 864e5).getDate();
}

/**
 * 获取当前几个月前的日期
 * @param {Number} totalMonth 需要获取几个月
 * @returns {Array} totalMonth = 6 返回['2022-1', '2021-12', '2021-11', '2021-10', '2021-9', '2021-8']，当前时间为2022-1-12
 */
date.getRecentMonths = function (totalMonth) {
  // 六个月数据 ['2022-1', '2021-12', '2021-11', '2021-10', '2021-9', '2021-8']
  let datelist = []
  let date = new Date()
  let Y = date.getFullYear()
  let M = date.getMonth()+1 //0-11月
  for (let i = 0; i < totalMonth; i++) {
    let dateoption = ''
    if (M !== 0) {} else {
      M = 12
      Y = Y - 1
    }
    let m = M
    // m = m < 10 ? '0' + m : m
    dateoption = Y + '-' + m
    M--
    datelist.push(dateoption)
  }
  return datelist
}

/**
 * 求date加几天或减几天后的日期
 */
date.addHour = function(d, gap){
  let dateTime = d.setHours(d.getHours()+gap);
  return new Date(dateTime);
}

/**
 * 求date加几天或减几天后的日期
 */
date.addDay = function(date, gap){
  let dateTime = date.setDate(date.getDate()+gap);
  return new Date(dateTime);
}

/**
 * 求date加几月或减几月后的日期
 */
date.addMonth = function(date, gap){
  let dateTime = date.setMonth(date.getMonth()+gap);
  return new Date(dateTime);
}

/**
 * 求date加几年或减几年后的日期
 */
date.addYear = function(date, gap){
  let dateTime = date.setFullYear(date.getFullYear()+gap);
  return new Date(dateTime);
}

/**
 * 获取过去几年时间数组
 */
date.getLastFewYear = function(n, invert = false){
  let arr = []
  if(invert){
    for(var i = 0; i < n; ++i){
      let d = this.addYear(new Date(), -(i))
      arr.push(this.formatDate(d, 'yyyy') + '')
    }
  } else {
    for(var i = n-1; i >= 0; --i){
      let d = this.addYear(new Date(), -i)
      arr.push(this.formatDate(d, 'yyyy') + '')
    }
  }
  return arr
}

/**
 * 获取过去几月时间数组
 */
 date.getLastFewMonth = function(n, invert = false){
  let arr = []
  if(invert){
    for(var i = 0; i < n; ++i){
      let d = this.addMonth(new Date(), -(i))
      arr.push(this.formatDate(d, 'yyyy-MM') + '')
    }
  } else {
    for(var i = n-1; i >= 0; --i){
      let d = this.addMonth(new Date(), -i)
      arr.push(this.formatDate(d, 'yyyy-MM') + '')
    }
  }
  return arr
}

/**
 * 获取过去几天时间数组
 */
 date.getLastFewDay = function(n, invert = false){
  let arr = []
  if(invert){
    for(var i = 0; i < n; ++i){
      let d = this.addDay(new Date(), -(i))
      arr.push(this.formatDate(d, 'yyyy-MM-dd') + '')
    }
  } else {
    for(var i = n-1; i >= 0; --i){
      let d = this.addDay(new Date(), -i)
      arr.push(this.formatDate(d, 'yyyy-MM-dd') + '')
    }
  }
  return arr
}

/**
 * 获取过去几小时时间数组
 */
 date.getLastFewHour = function(n, invert = false){
  let arr = []
  if(invert){
    for(var i = 0; i < n; ++i){
      let d = this.addHour(new Date(), -(i))
      arr.push(this.formatDate(d, 'hh') + '')
    }
  } else {
    for(var i = n-1; i >= 0; --i){
      let d = this.addHour(new Date(), -i)
      arr.push(this.formatDate(d, 'hh') + '')
    }
  }
  return arr
}

/**
 * 获取星期几
 * @param { String } time 需要转换的时间 
 * @returns 返回目标时间的星期几
 */
date.getWeekday = function(time) {
  let targetTime = time ? new Date(time) : new Date();
  let res = targetTime.getDay();
  switch(res) {
    case 0:
      return '星期日';
    case 1:
      return '星期一';
    case 2:
      return '星期二';
    case 3:
      return '星期三';
    case 4:
      return '星期四';
    case 5:
      return '星期五';
    case 6:
      return '星期六';
  }
}

/**
 * 获取指定日期所在月份的起始日期和结束日期
 * @param {*} date 指定日期
 * @returns 所在月份的起始日期和结束日期
 */
date.getMonthDay = function(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
  let d = date ? new Date(date) : new Date();
  let year = d.getFullYear();
  let month = d.getMonth();
  let totalDays = this.checkDateTotalDays(year, month+1);
  let monthStart = this.formatDate(new Date(year, month, 1), fmt);
  let monthEnd = this.formatDate(new Date(year, month, totalDays, 23, 59, 59), fmt);
  return [monthStart, monthEnd];
}

export default date;
